//
//  DZBarCodeManager.swift
//  DZFoundation
//
//  Created by Darren Zheng on 15/10/10.
//  Copyright © 2015年 Darren Zheng. All rights reserved.
//

import UIKit
import AVFoundation

@objc class DZBarCodeManager: NSObject, AVCaptureMetadataOutputObjectsDelegate
{
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height
    var line   : UIImageView!
    var traceNumber = 0
    var upORdown = false
    var timer:NSTimer!
    
    let screenSize = UIScreen.mainScreen().bounds.size
    var closure: (barcode: String)->()
    let captureSession = AVCaptureSession()
    
    init(view: UIView!, completion:(barcode: String)->())
    {
        closure = completion
        
        super.init()
        
        do
        {
            // Device
            let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
            
            // DeviceInput <- Device
            let input = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput
            
            // Session <- DeviceInput
            captureSession.addInput(input)
            
            // Session <- MetadataOutput
            let metadata = AVCaptureMetadataOutput()
            captureSession.addOutput(metadata)
            metadata.metadataObjectTypes = metadata.availableMetadataObjectTypes
            metadata.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
            
            // VideoPreviewLayer <- Session
            let captureLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            captureLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            captureLayer.frame = view.frame
            view.layer.addSublayer(captureLayer)
        }
        catch let error as NSError
        {
            print(error)
        }
    }
    
    func startRunning()
    {
        // Session -> Start
        captureSession.startRunning()
    }
    
    func stopRunning()
    {
        // Session -> Stop
        captureSession.stopRunning()
    }
    
    // output delegete
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
    {
        for metaData in metadataObjects
        {
            let decodedData:AVMetadataMachineReadableCodeObject = metaData as! AVMetadataMachineReadableCodeObject
            closure(barcode: decodedData.stringValue)
        }
    }

}
